//
//  YOUfanLocationUtils.m
//  NewYoufanApp
//
//  Created by 九月 on 7/20/24.
//

#import "YOUfanLocationUtils.h"

//#import "BRPickerView.h"
#import "YYModel.h"
//#import "YOUfanCityModel.h"
//#import "BRAddressPickerView.h"

@interface YOUfanLocationUtils () <CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;
/// 定位成功的回调block
@property (nonatomic, copy) void (^successBlock)(NSArray<CLLocation *> *);
/// 编码成功的回调block
@property (nonatomic, copy) void (^geocodeBlock)(NSArray *geocodeArray);
/// 定位失败的回调block
@property (nonatomic, copy) void (^failureBlock)(NSError *error);

@property (nonatomic, copy) void (^fyanouLocationValueBlock)(NSString *longitude, NSString *latitude);


@property (assign, nonatomic) BOOL fyanouHaveReportLocation;

@end

@implementation YOUfanLocationUtils


+ (instancetype)manager {
    static YOUfanLocationUtils *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
        manager.locationManager = [[CLLocationManager alloc] init];
        manager.locationManager.delegate = manager;
        [manager.locationManager requestWhenInUseAuthorization];
    });
    return manager;
}

- (BOOL)fyanouCanUseLocation {
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    return status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusAuthorizedAlways;
}

- (void)checkAuthorizationStatus {
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            // 用户尚未做出选择
            NSLog(@"用户尚未做出选择");
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse:
        case kCLAuthorizationStatusAuthorizedAlways:
            // 用户已经授权
            if (!self.locationManager.locationServicesEnabled) {
                // 定位服务未开启
                NSLog(@"定位服务未开启");
                break;
            }
            // 可以在这里开始使用定位服务
            break;
        case kCLAuthorizationStatusDenied:
        case kCLAuthorizationStatusRestricted:
            // 用户拒绝或系统限制了定位权限
            NSLog(@"用户拒绝或系统限制了定位权限");
            break;
        default:
            break;
    }
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    [self checkAuthorizationStatus];
}


- (void)fyanouStartLocation {
//    [self startLocationWithSuccessBlock:nil failureBlock:nil geocoderBlock:nil];
    [self.locationManager startUpdatingLocation];
}

- (void)startLocationWithSuccessBlock:(void (^)(NSArray<CLLocation *> *))successBlock failureBlock:(void (^)(NSError *error))failureBlock {
    [self startLocationWithSuccessBlock:successBlock failureBlock:failureBlock geocoderBlock:nil];
}

- (void)startLocationWithGeocoderBlock:(void (^)(NSArray *geocoderArray))geocoderBlock {
    [self startLocationWithSuccessBlock:nil failureBlock:nil geocoderBlock:geocoderBlock];
}

- (void)startLocationToSuccessBlock:(void (^)(NSString *longitude, NSString *latitude))heiyouBlock {
    [self fyanouStartLocationToSuccess:heiyouBlock ];
}

- (void)startLocationWithSuccessBlock:(void (^)(NSArray<CLLocation *> *))successBlock failureBlock:(void (^)(NSError *error))failureBlock geocoderBlock:(void (^)(NSArray *geocoderArray))geocoderBlock {
    [self.locationManager startUpdatingLocation];
    _successBlock = successBlock;
    _geocodeBlock = geocoderBlock;
    _failureBlock = failureBlock;
}

- (void)fyanouStartLocationToSuccess:(void (^)(NSString *longitude, NSString *latitude))heiyouBlock {
    [self.locationManager startUpdatingLocation];
    self.fyanouLocationValueBlock = heiyouBlock;
}


- (void)stopUpdatingLocation {
    [self.locationManager stopUpdatingLocation];
}



#pragma mark - CLLocationManagerDelegate

/// 地理位置发生改变时触发
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    [manager stopUpdatingLocation];
    
//    if (_successBlock) {
//        _successBlock(locations);
//    }
//    
//    if (self.fyanouLocationValueBlock) {
//
//    }
//    
//    if (_geocodeBlock && locations.count) {
//        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
//        [geocoder reverseGeocodeLocation:[locations firstObject] completionHandler:^(NSArray *array, NSError *error) {
//            self->_geocodeBlock(array);
//        }];
//    }
    if (locations.count) {
        CLLocation *heiyou = [locations lastObject];
        
        self.fyanouLon = [NSString stringWithFormat:@"%f",heiyou.coordinate.longitude];
        self.fyanouLat = [NSString stringWithFormat:@"%f",heiyou.coordinate.latitude];
        
        if ( self.ttatheDidLocationChange) {
            self.ttatheDidLocationChange();
        }
        if (!self.fyanouHaveReportLocation) {
            __weak typeof(self) fyweakSelf = self;

        }
    }
}

- (void)heiyouGetCityName:(void (^)(NSString *heiyouName, NSString *fanfanCode))heiyouBlock {
    CLLocation *heiyou = [[CLLocation alloc] initWithLatitude:self.fyanouLat.doubleValue longitude:self.fyanouLon.doubleValue];
    CLGeocoder *feiwu = [[CLGeocoder alloc]init];
    __weak typeof(self) fyweakSelf = self;
    
    [feiwu reverseGeocodeLocation:heiyou completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count > 0) {
            CLPlacemark *nearbyYouquPlaceMark = placemarks[0];
            NSString *nearbyYouquCurrentCity = nearbyYouquPlaceMark.locality;
            NSString *cityCode = nearbyYouquPlaceMark.postalCode;
            __strong typeof(fyweakSelf) fystrongSelf = fyweakSelf;
            fystrongSelf.ttotheCityName = nearbyYouquCurrentCity;
            
            heiyouBlock(nearbyYouquCurrentCity, cityCode);
        }
    }];
}

//- (NSArray <YOUfanCityModel *>*)heiyouGetCitySubsWith:(NSString *)fanfanCode {
//    NSArray *fanfan = self.heiyouAddressJsonArray;
////    NSLog(@"ssdaf = %@", aa);
//    for (YOUfanCityModel *heiyou in fanfan) {
//        for (YOUfanCityModel *heiyouCity in heiyou.cityList) {
//            if ([heiyouCity.name isEqualToString:fanfanCode]) {
//                return heiyouCity.cityList;
//            }
//        }
//    }
//    return @[];
//}
//
//- (NSArray <YOUfanCityModel *>*)heiyouAddressJsonArray {
//    static NSArray *cityArray = nil;
//    if (!cityArray) {
//        // 获取 BRAddressPickerView.bundle
//        NSBundle *containnerBundle = [NSBundle bundleForClass:[BRAddressPickerView class]];
//        NSString *bundlePath = [containnerBundle pathForResource:@"BRAddressPickerView" ofType:@"bundle"];
//        NSBundle *addressPickerBundle = [NSBundle bundleWithPath:bundlePath];
//        
//        // 获取bundle中的JSON文件
//        NSString *filePath = [addressPickerBundle pathForResource:@"BRCity" ofType:@"json"];
//        NSData *data = [NSData dataWithContentsOfFile:filePath];
////        cityArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//        
//        cityArray = [NSArray yy_modelArrayWithClass:[YOUfanCityModel class] json:data];
//    }
//    return cityArray;
//}

/// 定位失败回调方法
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    switch([error code]) {
        case kCLErrorDenied: { // 用户禁止了定位权限
            
        } break;
        default: break;
    }
    if (_failureBlock) {
        _failureBlock(error);
    }
}

- (NSString *)fyanouLat {
    if (!_fyanouLat) {
        _fyanouLat = @"";
    }
    return _fyanouLat;
}

- (NSString *)fyanouLon {
    if (!_fyanouLon) {
        _fyanouLon = @"";
    }
    return _fyanouLon;
}


@end
